<template>
  <div class="content">
    <!-- 复检结果 -->
    <div class="content-table">
      <el-form
        :model="formData"
        ref="formRef"
        label-width="100px"
        class="form__content"
      >
        <!-- :rules="formRules" -->
        <div class="divider">复检结果:</div>
        <el-table :data="cacheIsContentList" border>
          <!-- :span-method="objectSpanMethod" -->

          <el-table-column
            label="序号"
            type="index"
            width="50"
          ></el-table-column>
          <el-table-column prop="content" label="检查内容"></el-table-column>
          <el-table-column prop="requests" label="标准要求"> </el-table-column>
          <el-table-column label="检查方法">
            <template #default="{ row }">
              <el-input v-model="row.insMethod"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="检查小结">
            <template #default="{ row }">
              <el-input v-model="row.insSummary"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否合格" width="180">
            <template #default="{ row }">
              <el-radio-group
                v-model="row.isQualifiedCheck"
                @change="handleCheck(row)"
              >
                <el-radio label="1">合格</el-radio>
                <el-radio label="0">不合格</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="附件">
            <template #default="{ row }">
              <!-- class="upload-demo" -->
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :accept="acceptTypes"
                name="uploadFile"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-error="handleError"
                :on-success="handleSuccess"
                :on-preview="handlePreview"
                :show-file-list="false"
              >
                <el-button
                  size="small"
                  type="text"
                  @click="handleUpload(row.id)"
                  >点击上传</el-button
                >
              </el-upload>
              <div
                v-for="item in row.insContentAttachmentArr"
                :key="item?.uuidFile"
              >
                <div class="file-item">
                  <div
                    class="file-item--left"
                    @click.prevent="handleDownload2(item)"
                    :title="item.fileName"
                  >
                    <i class="el-icon-folder"></i>{{ item?.fileName }}
                  </div>
                  <div
                    class="file-item--right"
                    @click="handleDelete2(item, row.id)"
                  >
                    删除
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="整改意见">
            <template #default="{ row }">
              <el-input v-model="row.recOpinions"></el-input>
            </template>
          </el-table-column> -->
        </el-table>
      </el-form>
    </div>

    <div class="content-table" v-if="isError">
      <el-form
        :model="formData"
        ref="formRef"
        label-width="100px"
        class="form__content"
      >
        <!-- :rules="formRules" -->
        <div class="divider">整改内容:</div>
        <el-table :data="filterFormDataEdit2(cacheIsContentList)" border>
          <!-- :span-method="objectSpanMethod" -->

          <el-table-column
            label="序号"
            type="index"
            width="50"
          ></el-table-column>
          <el-table-column prop="content" label="检查内容"></el-table-column>
          <el-table-column prop="requests" label="标准要求"> </el-table-column>
          <el-table-column label="检查方法">
            <template #default="{ row }">
              <el-input disabled v-model="row.insMethod"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="检查小结">
            <template #default="{ row }">
              <el-input disabled v-model="row.insSummary"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否合格" width="180">
            <template #default="{ row }">
              <el-radio-group v-model="row.isQualifiedCheck">
                <el-radio disabled label="1">合格</el-radio>
                <el-radio disabled label="0">不合格</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="附件">
            <template #default="{ row }">
              <div
                v-for="item in row.insContentAttachmentArr"
                :key="item?.uuidFile"
              >
                <div class="file-item">
                  <div
                    class="file-item--left"
                    @click.prevent="handleDownload2(item)"
                    :title="item.fileName"
                  >
                    <i class="el-icon-folder"></i>{{ item?.fileName }}
                  </div>
                </div>
              </div>
              <div v-if="!row.insContentAttachmentArr.length">--</div>
            </template>
          </el-table-column>
          <el-table-column label="整改意见">
            <template #default="{ row }">
              <el-input v-model="row.recOpinions"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <p class="divider">
      <span class="required">*</span>{{ isError ? "整改意见：" : "检查意见：" }}
    </p>
    <el-form
      :model="formData"
      ref="formRef"
      class="form__content"
      :rules="formRules"
    >
      <el-form-item label="" prop="recOpinions">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          v-model="formData.recOpinions"
        ></el-input>
      </el-form-item>
    </el-form>

    <div class="content-footer">
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
    </div>
    <el-dialog
      title="质量复查"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <!-- <div class="dialog__content--title">任务基本信息:</div> -->
        <div style="width: 100%; text-align: center; padding: 20px 0">
          是否确定提交？
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  reactive,
  ref,
  watch,
  defineProps,
  onMounted,
  nextTick,
  computed
} from "vue";
import { useRouter, useRoute } from "vue-router";

import { storageLocal } from "/@/utils/storage";
import { download } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";
import { postFlowSubmit } from "/@/api/quality";
import { cloneDeep } from "lodash-es";
import { postGetStorageTmpData, postStorageTmpData } from "/@/api/acceptance";

import { acceptTypes, uploadUrl } from "../../types";
import { handleError, handlePreview } from "../../utils";

import ReButton from "/@/components/ReButton/index.vue";

const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

const props = defineProps({
  checkContentList: {
    type: Array,
    default: () => []
  },
  taskId: {
    type: String,
    default: ""
  },
  storageData: {
    type: Object,
    default: () => {}
  },
  projectTeam: {
    type: Array,
    default: () => []
  }
});

const formRef = ref<HTMLFormElement | null>(null) as any;
let formData = reactive({
  insContentList: [],
  recOpinions: "",
  recFeedback: ""
});

const formRules = ref({
  recOpinions: { required: true, message: "请填写意见", trigger: "change" }
});

let outterId = ref("");
let effective = ref("");

let currentTeam = reactive({
  userName: "",
  userId: ""
}); // 下一节点的处理人信息

let cacheCurrentUser = ref("");
let cacheCurrentName = ref("");

// let copeyContentList = ref([]);

// let copyRecOpinions = ref();

let commitVisible = ref(false);
const router = useRouter();
const route = useRoute();
// let spanArr = ref([]); // 用于存放每一行记录的合并数
// let pos = ref(null); // 用于存放每一行记录的合并数

let cacheIsContentList = ref([]);

watch(
  () => props.checkContentList,
  newVal => {
    if (newVal && newVal.length > 0) {
      formData.insContentList = cloneDeep(newVal);
      // copeyContentList.value = cloneDeep(newVal);
      formData.insContentList.forEach(item => {
        if (
          !item.insContentAttachmentArr ||
          !item.insContentAttachmentArr.length
        ) {
          item.insContentAttachmentArr = [];
        }
      });

      // filterFormDataEdit(formData.insContentList);
      const res = formData.insContentList.filter(item => {
        return item.isQualifiedCheck === "0";
      });

      res.forEach(i => {
        i.recOpinions = "";
        i.insContentAttachmentArr = [];
        // i.insMethod = "";
        i.insSummary = "";
        i.isQualifiedCheck = "1";
        i.isQualifiedRec = "1";
        i.recFeedbackDesc = "";
        i.rectificationTime = "";
      });

      cacheIsContentList.value = res;
      console.log(cacheIsContentList.value, "watch");

      nextTick(() => {
        // getSpanArr(formData.insContentList);
        getStorageTmpData();
      });
    }
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.storageData,
  newVal => {
    if (newVal.inspectName) {
      console.log(newVal);
      // formData.recOpinions = JSON.parse(
      //   JSON.stringify(props.storageData.recOpinions)
      // );

      // copyRecOpinions.value = formData.recOpinions;

      // formData.recFeedback = JSON.parse(
      //   JSON.stringify(props.storageData.recFeedback)
      // );

      // 流程发起人Id

      cacheCurrentUser.value = JSON.parse(
        JSON.stringify(props.storageData.inspectorId)
      );
      cacheCurrentName.value = JSON.parse(
        JSON.stringify(props.storageData.inspectorName)
      );
    }
  },
  {
    deep: true,
    immediate: true
  }
);

// const formRules = {
//   remarks: { required: true, message: "请填写审批意见", trigger: "change" }
// };

// const filterFormData = list => {
//   const res = list.filter(item => {
//     return item.isQualifiedCheck === "0";
//   });
//   return cloneDeep(res);
// };

// const filterFormDataEdit = list => {
//   const res = JSON.parse(
//     list.filter(item => {
//       return item.isQualifiedCheck === "0";
//     })
//   );
//   res.forEach(i => {
//     i.recOpinions = "";
//     i.insContentAttachmentArr = [];
//     i.insMethod = "";
//     i.insSummary = "";
//     i.isQualifiedCheck = "1";
//   });

//   cacheIsContentList.value = res;
// };

const filterFormDataEdit2 = list => {
  const res = list.filter(item => {
    return item.isQualifiedCheck === "0";
  });
  // res.forEach(i => {
  //   i.recOpinions = "";
  //   i.insContentAttachmentArr = [];
  //   i.insMethod = "";
  //   i.insSummary = "";
  // });

  return res;
};

const isError = computed(() => {
  console.log(cacheIsContentList.value, "cacheIsContentList.value");
  const errList = cacheIsContentList.value.filter(item => {
    return item.isQualifiedCheck === "0";
  });
  if (errList.length > 0) {
    return true;
  } else {
    return false;
  }
});

// 是否合格
const handleCheck = row => {
  if (row.isQualifiedCheck === "0") {
    row.isQualifiedRec = "0";
  } else {
    row.isQualifiedRec = "1";
    row.recOpinions = "";
  }
};

// 文件上传
let cacheTableItem = ref(0);

const handleUpload = index => {
  // console.log(index, "222");
  cacheTableItem.value = index;
};

const handleRemove = (file, fileList) => {
  // defaultFileList.value = fileList;
  console.log(file, fileList);
};

const handleChange = (file, fileList) => {
  console.log(file, fileList);

  // console.log(formData.insContentList, "formData.insContentList", fileList);
  // formData.insContentList[cacheTableItem].insContentAttachmentArr =
  //   formData.insContentList[cacheTableItem].insContentAttachmentArr.concat(fileList);
  // defaultFileList.value = fileList;
  // formRef.value.clearValidate();
};

const handleSuccess = file => {
  if (file.code === 200) {
    let cacheIndex = null;
    cacheIsContentList.value.forEach((item, index) => {
      if (item.id === cacheTableItem.value) {
        cacheIndex = index;
      }
    });
    cacheIsContentList.value[cacheIndex].insContentAttachmentArr.push(
      file.data
    );
    console.log(formData.insContentList, " formData.insContentList");
    // formData.insContentList[cacheTableItem.value].insContentAttachmentArr.push(
    //   file.data
    // );
  }
};

// table 处理相关--------------------------------------
// const getSpanArr = data => {
//   // data就是我们从后台拿到的数据
//   for (let i = 0; i < data.length; i++) {
//     if (i === 0) {
//       spanArr.value.push(1);
//       pos.value = 0;
//     } else {
//       // 判断当前元素与上一个元素是否相同
//       if (data[i].content === data[i - 1].content) {
//         spanArr.value[pos.value] += 1;
//         spanArr.value.push(0);
//       } else {
//         spanArr.value.push(1);
//         pos.value = i;
//       }
//     }
//   }
// };
// const objectSpanMethod = ({ rowIndex, columnIndex }) => {
//   if (columnIndex === 1) {
//     const _row = spanArr.value[rowIndex];
//     const _col = _row > 0 ? 1 : 0;
//     // console.log(`rowspan:${_row} colspan:${_col}`);
//     return {
//       // [0,0] 表示这一行不显示， [2,1]表示行的合并数
//       rowspan: _row,
//       colspan: _col
//     };
//   }
// };

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/quality/inspection", replace: true });
  }
};

const handleSubmit = async () => {
  const errList = cacheIsContentList.value.filter(item => {
    return item.isQualifiedCheck === "0";
  });
  // 如果大于0则继续整改
  const isPass = errList.length > 0 ? false : true;
  // currentTeam.userName = cacheCurrentName.value;
  // currentTeam.userId = cacheCurrentUser.value;
  props.projectTeam.forEach(item => {
    if (!isPass) {
      if ((item as any)?.roleCode === "4") {
        currentTeam.userName = (item as any)?.userName;
        currentTeam.userId = (item as any)?.userId;
      }
    } else {
      if ((item as any)?.roleCode === "1") {
        currentTeam.userName = (item as any)?.userName;
        currentTeam.userId = (item as any)?.userId;
      }
    }
  });

  if (!currentTeam.userId) {
    NotifMessage.error("该合同未配置项目组成员，请先前往配置");
  } else {
    commitVisible.value = true;
  }
  console.log(currentTeam, "currentTeam");
};

const handleRequest = async done => {
  try {
    const { instanceId, nodeDefId, flowId, contractId } = route.query;
    const info = storageLocal.getItem("info");

    // 如果复检还是0 则继续整改
    const errList = cacheIsContentList.value.filter(item => {
      return item.isQualifiedCheck === "0";
    });
    // 如果大于0则继续整改
    const isPass = errList.length > 0 ? false : true;

    const newFormData = JSON.parse(JSON.stringify(formData));
    const newSaveFormData = JSON.parse(JSON.stringify(formData));

    // const isOKFormData = newFormData.insContentList.filter(item => {
    //   return item.isQualifiedRec === "1";
    // });
    const newList = JSON.parse(JSON.stringify(cacheIsContentList.value));
    // 提交保存时的缓存
    newSaveFormData.insContentList = newList;

    newFormData.insContentList.forEach((item, index) => {
      newList.forEach(i => {
        if (i.id === item.id) {
          newFormData.insContentList[index] = i;
        }
      });
    });

    // console.log(isOKFormData, "isOKFormData", cacheIsContentList.value);
    // newFormData.insContentList = isOKFormData;

    // newFormData.insContentList = newFormData.insContentList.concat(newList);
    console.log(newFormData, "newFormData");
    const params = {
      formBaseInfo: {
        id: contractId,
        ...newFormData
      },
      formSubMap: {
        flowType: 11,
        nodeId: nodeDefId,
        isRectification: "", // 质量整改通过传0
        recheckPass: isPass ? "1" : "0", // 质量复查通过传1
        isChargehand: "",
        flowId,
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `${isPass ? "整改反馈" : "检查意见"}：${
          newFormData.recOpinions
        }`,
        assignee: currentTeam.userId
      },
      tmpStorage: {
        nodeId: nodeDefId,
        flowId,
        taskId: props.taskId,
        handlerId: info?.userId ?? "",
        userId: info?.userId ?? "",
        valueJson: JSON.stringify({
          ...newSaveFormData,
          flowInfoId: flowId
        })
      }
    };

    // 根据后端要求。传一个outterId
    if (outterId.value) {
      const joinData = Object.assign(params.tmpStorage, {
        outterId: outterId.value
      });
      params.tmpStorage = joinData;
    }
    // 根据后端要求。传一个effective
    if (effective.value) {
      const joinData = Object.assign(params.tmpStorage, {
        effective: effective.value
      });
      params.tmpStorage = joinData;
    }
    console.log(params);

    const { code, data } = await postFlowSubmit(params);
    console.log(code, data);
    if (code === 200) {
      NotifMessage.success("提交成功");
      handleBack();
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

const handleSave = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let newFormData = JSON.parse(JSON.stringify(formData));
  console.log(cacheIsContentList.value);
  newFormData.insContentList = cacheIsContentList.value;
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : "",
    valueJson: JSON.stringify(newFormData)
  };

  if (outterId.value) {
    params = Object.assign(params, { outterId: outterId.value });
  }

  if (effective.value) {
    params = Object.assign(params, { effective: effective.value });
  }

  try {
    const { code, message } = await postStorageTmpData(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { insContentList, recOpinions, recFeedback } = JSON.parse(
        data.valueJson
      );
      console.log(insContentList, "insContentList");

      cacheIsContentList.value = insContentList;

      // formData.insContentList = cloneDeep(insContentList);
      // // copeyContentList.value = cloneDeep(insContentList);
      // formData.insContentList.forEach(item => {
      //   if (
      //     !item.insContentAttachmentArr ||
      //     !item.insContentAttachmentArr.length
      //   ) {
      //     item.insContentAttachmentArr = [];
      //   }
      // });

      formData.recOpinions = JSON.parse(JSON.stringify(recOpinions));
      formData.recFeedback = JSON.parse(JSON.stringify(recFeedback));

      outterId.value = data.outterId;
      effective.value = data?.effective ?? "";
    }
  }

  // nextTick(() => {
  //   getSpanArr(formData.insContentList);
  // });
};

const handleDownload2 = item => {
  if (!item) return;
  download(item);
};

const handleDelete2 = (item, indexId) => {
  let cacheIndex = null;
  formData.insContentList.forEach((item, index) => {
    if (item.id === indexId) {
      cacheIndex = index;
    }
  });
  formData.insContentList[cacheIndex].insContentAttachmentArr =
    formData.insContentList[cacheIndex].insContentAttachmentArr.filter(i => {
      return item.uuidFile !== i.uuidFile;
    });
};

onMounted(() => {
  nextTick(() => {
    // getStorageTmpData();
  });
});
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  &-table {
    margin-bottom: 20px;
    p {
      padding: 10px 0;
    }
  }
  &-footer {
    margin-top: 20px;
    width: inherit;
    height: 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.divider {
  margin-bottom: 10px;
  // border-left: 3px solid #409eff;
  text-indent: 8px;
  .required {
    color: rgb(245, 108, 108);
    margin-right: 4px;
  }
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  &--left {
    flex: 1;
    margin-right: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    .el-icon-folder {
      margin-right: 5px;
    }
    &:hover {
      cursor: pointer;
      color: #409eff;
    }
  }
  &--right {
    font-size: 10px;
    width: 40px;
    text-align: center;
    color: red;
  }
}
</style>
